/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2025-06-25     29922       the first version
 */
#include <rtthread.h>
#include <rtdevice.h>
#include "cyhal.h"

#define DBG_TAG "light"
#define DBG_LVL DBG_INFO
#include <rtdbg.h>

#define ADC_DEV_NAME        "adc1"
#define ADC_DEV_CHANNEL     (P10_1)

struct rt_messagequeue mq;
static rt_uint8_t msg_pool[2048];

static void get_lightness(void* parameter)
{
    rt_uint32_t value;
    rt_err_t ret = RT_EOK;
    rt_uint8_t lightness;
    rt_adc_device_t adc_dev;

    adc_dev = (rt_adc_device_t)rt_device_find(ADC_DEV_NAME);

    if(adc_dev == RT_NULL)
    {
        LOG_E("can't find %s device!\n",ADC_DEV_NAME);
        return;
    }

    ret = rt_adc_enable(adc_dev, ADC_DEV_CHANNEL);

    if(ret != RT_EOK)
    {
        LOG_E("enable %s %s failed!\n",ADC_DEV_NAME,ADC_DEV_CHANNEL);
    }

    while(RT_TRUE)
    {
        value = rt_adc_read(adc_dev, ADC_DEV_CHANNEL);
        value = value > 3300 ? 0 :value;
        lightness = (double)value / 3298 *50;
        LOG_D("ligjtness queue send lightness failed!");
        ret = rt_mq_send(&mq, &lightness, sizeof(rt_uint8_t));
        if(ret != RT_EOK)
        {
            LOG_E("message queue send lightness failed!");
        }
        rt_thread_mdelay(1000);

    }
}

rt_err_t app_lightness(void)
{
    rt_err_t ret;
    ret = rt_mq_init(&mq, "mqt", &msg_pool[0], sizeof(rt_uint8_t), sizeof(msg_pool),RT_IPC_FLAG_PRIO);

    if(ret != RT_EOK)
    {
        LOG_E("init message queue failed\n");
        return -1;
    }

    rt_thread_t lightness_t = rt_thread_create("lightness", get_lightness, RT_NULL, 2048, 14, 5);

    if(lightness_t != RT_NULL)
    {
        ret = rt_thread_startup(lightness_t);
    }
    return ret;
}



